package com.furns.web;

import com.furns.entity.Furn;
import com.furns.entity.Page;
import com.furns.service.FurnService;
import com.furns.service.impl.FurnServiceImpl;
import com.furns.utils.DataUtils;
import com.furns.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author LuoJiaCheng
 * @ID 2240129126
 * @Version 1.0
 */
@WebServlet(name = "FurnServlet", value = "/manage/FurnServlet")
public class FurnServlet extends BasicServlet{
    //定义属性
    private FurnService furnService =new FurnServiceImpl();


    /**
     * 使用反射+动态绑定调用list方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Furn> furns = furnService.queryFurns();
        //放入request
        req.setAttribute("furns",furns);
        //请求转发
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req,resp);
    }

    /**
     * 添加家居
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addFurn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String name = req.getParameter("name");
//        String maker = req.getParameter("maker");
//        String price = req.getParameter("price");
//        String sales = req.getParameter("sales");
//        String stock = req.getParameter("stock");
//        Furn furn = null;
//        //添加数据格式错误
//        try {
//            furn = new Furn(null, name, maker, new BigDecimal(price), new Integer(sales), new Integer(stock), "assets/images/product-image/default.jpg");
//        } catch (NumberFormatException e) {
//            req.setAttribute("msg","添加数据格式错误");
//            req.getRequestDispatcher("/views/manage/furn_add.jsp").forward(req,resp);
//            return;
//        }

//        Furn furn = new Furn();
//        try {
//            BeanUtils.populate(furn,req.getParameterMap());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
        //添加成功
        if(furnService.addFurn(furn)==1){
            //使用请求转发刷新请求会重复添加家居
            //使用重定向解决
            resp.sendRedirect(req.getContextPath()+"/manage/FurnServlet?action=page&pageNo="+req.getParameter("pageNo"));
        }else{
            req.getRequestDispatcher("/views/manage/furn_add.jsp").forward(req,resp);

        }

    }

    /**
     * 删除家居
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteFurn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"),0);
        furnService.deleteFurnById(id);
        //防止重复删除使用重定向
        resp.sendRedirect(req.getContextPath()+"/manage/FurnServlet?action=page&pageNo="+req.getParameter("pageNo"));

    }


    /**
     * 请求要修改的家居的信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showFurn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String id = req.getParameter("id");
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        req.setAttribute("furn",furn);
        //req.setAttribute("pageNo",req.getParameter("pageNo"));
        req.getRequestDispatcher("/views/manage/furn_update.jsp").forward(req,resp);
    }

    /**
     * 对家居信息处理正式修改
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
//    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
//        if(furnService.updateFurn(furn)==1){
//          //  resp.sendRedirect(req.getContextPath()+"/manage/FurnServlet?action=list");
//            //考虑分页
//            resp.sendRedirect(req.getContextPath()+"/manage/FurnServlet?action=page&pageNo="+req.getParameter("pageNo"));
//        }else{
//            req.getRequestDispatcher("/views/manage/furn_update.jsp").forward(req,resp);
//        }
//    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 判断是不是文件表单(enctype="multipart/form-data")
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        //todo furn如果为空不处理
        if(furn==null){
           return;
        }
        if (ServletFileUpload.isMultipartContent(req)) {
            //System.out.println("OK");
            //2. 创建 DiskFileItemFactory 对象, 用于构建一个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //3. 创建一个解析上传数据的工具对象

            ServletFileUpload servletFileUpload =
                    new ServletFileUpload(diskFileItemFactory);
            //解决接收到文件名是中文乱码问题
            servletFileUpload.setHeaderEncoding("utf-8");

            //4. 关键的地方, servletFileUpload 对象可以把表单提交的数据text / 文件
            //   将其封装到 FileItem 文件项中

            try {
                List<FileItem> list = servletFileUpload.parseRequest(req);

                //遍历，并分别处理=> 自然思路
                for (FileItem fileItem : list) {
                    //System.out.println("fileItem=" + fileItem);
                    //判断是不是一个文件=> 你是OOP程序员
                    if (fileItem.isFormField()) {//如果是true就是文本 input text
                        if("name".equals(fileItem.getFieldName())){//家具名
                            furn.setName(fileItem.getString("utf-8"));
                        }else if("maker".equals(fileItem.getFieldName())){//制造商
                            furn.setMaker(fileItem.getString("utf-8"));
                        }else if("price".equals(fileItem.getFieldName())){//价格
                            furn.setPrice(new BigDecimal(fileItem.getString()));
                        }else if("sales".equals(fileItem.getFieldName())){//销量
                            furn.setSales(new Integer(fileItem.getString()));
                        }else if("stock".equals(fileItem.getFieldName())){//库存
                            furn.setStock(new Integer(fileItem.getString()));
                        }
                    } else {//是一个文件

                        //用一个方法
                        //获取上传的文件的名字
                        String name = fileItem.getName();
                        if(!name.equals("")) {
                            System.out.println("上传的文件名=" + name);

                            //把这个上传到 服务器的 temp下的文件保存到你指定的目录
                            //1.指定一个目录 , 就是我们网站工作目录下
                            String filePath = "/" + WebUtils.FURN_IMG_DIRECTORY;
                            //2. 获取到完整目录 [io/servlet基础]
                            String fileRealPath =
                                    req.getServletContext().getRealPath(filePath);

                            //3. 创建这个上传的目录=> 创建目录?=> Java基础
                            //   老师思路; 我们也一个工具类，可以返回 /2024/11/11 字符串
                            File fileRealPathDirectory = new File(fileRealPath+"/"+WebUtils.getYearMothDay());
                            if (!fileRealPathDirectory.exists()) {//不存在，就创建
                                fileRealPathDirectory.mkdirs();//创建
                            }

                            //4. 将文件拷贝到fileRealPathDirectory目录
                            //   构建一个上传文件的完整路径 ：目录+文件名
                            //   对上传的文件名进行处理, 前面增加一个前缀，保证是唯一即可, 不错
                            name = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + name;
                            String fileFullPath = fileRealPathDirectory + "/" + name;
                            fileItem.write(new File(fileFullPath));

                            fileItem.getOutputStream().close();
                            //更新家居的图片路径
                            furn.setImgPath(WebUtils.FURN_IMG_DIRECTORY + "/" + WebUtils.getYearMothDay()+name);

                        }

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("不是文件表单...");
        }

        furnService.updateFurn(furn);
        //可以请求转发到更新成功的页面
        req.getRequestDispatcher("/views/manage/update_ok.jsp").forward(req,resp);
    }

    /**
     * 处理分页请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pageNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用service对象获取Page对象
        Page<Furn> page = furnService.page(pageNo, pageSize);
        req.setAttribute("page",page);
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req,resp);

    }
}
